package com.sky.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

	//微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CategoryMapper categorymapper;
    @Autowired
    private DishMapper dishmapper;
    @Autowired
    private SetmealMapper setmealmapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());

        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);

        //如果是新用户，自动完成注册
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);//后绪步骤实现
        }

        //返回这个用户对象
        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }

	@Override
	public List<Category> categoryList(Integer type) {
		// TODO 自动生成的方法存根
		//调用mapper获取category的数据
		List<Category> categorylist = categorymapper.list(type);
		
		return categorylist;
	}

	@Override
	public List<DishVO> dishList(Long categoryId) {
		// TODO 自动生成的方法存根
		//调用mapper获取categoryId的数据
		 Dish dish = Dish.builder()
			        .categoryId(categoryId)
			        .status(StatusConstant.ENABLE)
			        .build();
		 List<Dish> dishlist = dishmapper.list(dish);
		 List<DishVO> dishVOList = new ArrayList<>();

	        for (Dish d : dishlist) {
	            DishVO dishVO = new DishVO();
	            BeanUtils.copyProperties(d,dishVO);

	            //根据菜品id查询对应的口味
	            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

	            dishVO.setFlavors(flavors);
	            dishVOList.add(dishVO);
	        }

		 
		 return dishVOList;
	}

	@Override
	public List<Setmeal> setmealList(Long categoryId) {
		// TODO 自动生成的方法存根
		//得到了setmeal
		List<Setmeal> setmeal = setmealmapper.setmealList(categoryId);
		//获取套餐的菜品
		return setmeal;
	}
	@Override
	public List<DishItemVO> getDishItemById(Long id) {
		// TODO 自动生成的方法存根
		  return setmealmapper.getDishItemBySetmealId(id);
	}
}